/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/*************************************************************************
 * File: timer.cpp
 *************************************************************************
 *\author: starlove
 *************************************************************************/

#include <platform/timer.h>

std::map<int, ITimer *> ITimer::m_Timers;

void ITimer::AddTimer(ITimer *pt)
{
	if(!pt)
		return;
	std::map<int, ITimer *>::iterator it = m_Timers.find(pt->GetPtr()->id);
	if(it != m_Timers.end())
		return;
	m_Timers.insert(std::pair<int, ITimer *>(pt->GetPtr()->id, pt));
}

void ITimer::DelTimer(ITimer *pt)
{
	if(!pt)
		return;
	pt->GetPtr()->is_complete = true;
}

void ITimer::DelTimer(int id)
{
	std::map<int, ITimer *>::iterator it = m_Timers.find(id);
	if(it != m_Timers.end())
	{
		ITimer *pt = (ITimer *)it->second;
		pt->GetPtr()->is_complete = true;
	}
}

void ITimer::CheckAllTimers()
{
	std::map<int, ITimer *>::iterator itPrev = m_Timers.end();
	std::map<int, ITimer *>::iterator it = m_Timers.begin();
	while(it != m_Timers.end())
	{
		ITimer *pt = (ITimer *)it->second;
		if(pt->GetPtr()->is_complete)
		{
			m_Timers.erase(it);
			it = itPrev;
			continue;
		}
		if(pt->GetPtr()->can_run())
		{
			pt->OnTimer(GetTimestamp());
		}
		itPrev = it;
		it ++;
	}
}
